package com.ufox.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ufox.entity.Result;
import com.ufox.utils.JWTUtil;
import com.ufox.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中token
        String token = request.getHeader("Authorization");

        log.info("---------------"+token);
        response.setContentType("application/json;charset=UTF-8");

        if(StringUtils.isBlank(token)){
            response.getWriter().println(JSON.toJSONString( Result.noLogin()) );
            return false;
        }


        String value = (String)redisUtils.get(token);
        if(StrUtil.isBlank(value)){
            response.getWriter().println(JSON.toJSONString( Result.noLogin()) );
            return false;
        }

        token = token.substring(7);
        try{
            //验证token
            JWTUtil.verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();

            response.getWriter().println(JSON.toJSONString( Result.noLogin()) );
            return false;
        }
    }
}
